package com.bookmanger.server.service.impl;

import com.bookmanger.common.result.Result;
import com.bookmanger.server.service.ISBNService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ISBNServiceImpl implements ISBNService {
    
    private static final String OPEN_LIBRARY_API_URL = "https://openlibrary.org/api/books";
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public Result getBookInfoByISBN(String isbn) {
        try {
            // 构建Open Library API请求URL
            String url = OPEN_LIBRARY_API_URL + 
                "?bibkeys=ISBN:" + isbn + 
                "&format=json&jscmd=data";
            
            log.info("请求Open Library API: {}", url);
            
            // 发送HTTP请求
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                // 解析响应
                JsonNode root = objectMapper.readTree(response.getBody());
                JsonNode bookNode = root.path("ISBN:" + isbn);
                
                if (bookNode.isMissingNode()) {
                    return Result.error("未找到ISBN为 " + isbn + " 的图书信息");
                }
                
                Map<String, Object> bookInfo = parseBookInfo(bookNode);
                return Result.success(bookInfo);
            } else {
                log.error("Open Library API请求失败，状态码: {}", response.getStatusCode());
                return Result.error("获取图书信息失败，状态码: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("获取ISBN {} 图书信息时发生错误", isbn, e);
            return Result.error("获取图书信息时发生错误: " + e.getMessage());
        }
    }
    
    @Override
    public Result getBookInfoByISBNs(List<String> isbns) {
        try {
            List<Map<String, Object>> books = new ArrayList<>();
            List<String> failedIsbns = new ArrayList<>();
            
            for (String isbn : isbns) {
                try {
                    // 构建Open Library API请求URL
                    String url = OPEN_LIBRARY_API_URL + 
                        "?bibkeys=ISBN:" + isbn + 
                        "&format=json&jscmd=data";
                    
                    // 发送HTTP请求
                    ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
                    
                    if (response.getStatusCode().is2xxSuccessful()) {
                        // 解析响应
                        JsonNode root = objectMapper.readTree(response.getBody());
                        JsonNode bookNode = root.path("ISBN:" + isbn);
                        
                        if (!bookNode.isMissingNode()) {
                            Map<String, Object> bookInfo = parseBookInfo(bookNode);
                            bookInfo.put("isbn", isbn);
                            books.add(bookInfo);
                        } else {
                            failedIsbns.add(isbn);
                        }
                    } else {
                        failedIsbns.add(isbn);
                    }
                } catch (Exception e) {
                    log.error("获取ISBN {} 图书信息时发生错误", isbn, e);
                    failedIsbns.add(isbn);
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("books", books);
            result.put("failedIsbns", failedIsbns);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("批量获取图书信息时发生错误", e);
            return Result.error("批量获取图书信息时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 解析图书信息
     */
    private Map<String, Object> parseBookInfo(JsonNode bookNode) {
        Map<String, Object> bookInfo = new HashMap<>();
        
        // 标题
        JsonNode titleNode = bookNode.path("title");
        if (!titleNode.isMissingNode()) {
            bookInfo.put("title", titleNode.asText());
        }
        
        // 作者
        JsonNode authorsNode = bookNode.path("authors");
        if (!authorsNode.isMissingNode() && authorsNode.isArray()) {
            List<String> authors = new ArrayList<>();
            for (JsonNode authorNode : authorsNode) {
                JsonNode nameNode = authorNode.path("name");
                if (!nameNode.isMissingNode()) {
                    authors.add(nameNode.asText());
                }
            }
            if (!authors.isEmpty()) {
                bookInfo.put("authors", authors);
            }
        }
        
        // 出版日期
        JsonNode publishDateNode = bookNode.path("publish_date");
        if (!publishDateNode.isMissingNode()) {
            bookInfo.put("publish_date", publishDateNode.asText());
        }
        
        // 出版社
        JsonNode publishersNode = bookNode.path("publishers");
        if (!publishersNode.isMissingNode() && publishersNode.isArray()) {
            List<String> publishers = new ArrayList<>();
            for (JsonNode publisherNode : publishersNode) {
                JsonNode nameNode = publisherNode.path("name");
                if (!nameNode.isMissingNode()) {
                    publishers.add(nameNode.asText());
                }
            }
            if (!publishers.isEmpty()) {
                bookInfo.put("publishers", publishers);
            }
        }
        
        // 页数
        JsonNode numberOfPagesNode = bookNode.path("number_of_pages");
        if (!numberOfPagesNode.isMissingNode()) {
            bookInfo.put("number_of_pages", numberOfPagesNode.asInt());
        }
        
        // 封面图片
        JsonNode coverNode = bookNode.path("cover");
        if (!coverNode.isMissingNode()) {
            JsonNode largeCoverNode = coverNode.path("large");
            if (!largeCoverNode.isMissingNode()) {
                bookInfo.put("cover_large", largeCoverNode.asText());
            }
            
            JsonNode mediumCoverNode = coverNode.path("medium");
            if (!mediumCoverNode.isMissingNode()) {
                bookInfo.put("cover_medium", mediumCoverNode.asText());
            }
        }
        
        return bookInfo;
    }
}